package com.example.controller;

import com.example.dao.DepartmentDao;
import com.example.dao.EmpployeeDao;
import com.example.pojo.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Collection;

/**
 * @PackageName:com.example.controller
 * @className:EmpController
 * @Description: 员工控制器
 * @author:朱楚利
 * @date:2021/5/11 14:38
 */
@Controller
public class EmpController {

    @Autowired
    private EmpployeeDao empployeeDao;
    @Autowired
    private DepartmentDao departmentDao;

    /***
     * @Description 获取员工列表
     * @Date 14:39 2021/5/11
     * @author 朱楚利
    */
    @RequestMapping("/emps")
    public String emps(Model model){
        Collection<Employee> allEmployees = empployeeDao.getAllEmployees();
        model.addAttribute("emps",allEmployees);
        return "emp/list";
    }

    /***
     * @Description 员工添加页面
     * @Date 15:20 2021/5/11
     * @author 朱楚利
    */
    @GetMapping("/emp")
    public String toAddPage(Model model) {
        model.addAttribute("departments",departmentDao.departments());
        return "emp/add" ;
    }

    @PostMapping("/emp")
    public String add(Employee employee){
        System.out.println(employee);
        empployeeDao.save(employee);
        return "redirect:/emps";
    }

    @GetMapping("/update/{id}")
    public String toUpdate(@PathVariable("id") Integer id,Model model){
        System.out.println("id===>"+id);
        model.addAttribute("departments",departmentDao.departments());
        model.addAttribute("emp",empployeeDao.getEmployeeByID(id));
        return "emp/update";
    }

    @PostMapping("/exUpdate")
    public String exUpdate(Employee employee){
        empployeeDao.save(employee);
        return "redirect:/emps";
    }

    @RequestMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
        empployeeDao.deleteEmployeeByID(id);
        return "redirect:/emps";
    }
}
